﻿using duia.Canteenpay.Application.Querys;
using duia.Canteenpay.Domain;
using duia.Canteenpay.Domain.DomainObject;
using duia.Canteenpay.Domain.IRepository;
using duia.Canteenpay.ViewModel.Users;
using System;
using System.Threading.Tasks;

namespace duia.Canteenpay.Application.AppService
{
    /// <summary>
    /// 系统用户管理
    /// </summary>
    public class UsersAppService
    {
        private readonly IUserRepository _userRepository;


        public readonly UserQuerys Querys;

        public UsersAppService(IUserRepository userRepository, UserQuerys userQuerys)
        {
            _userRepository = userRepository;
            Querys = userQuerys;
        }

        /// <summary>
        /// 新增系统用户
        /// </summary>
        /// <param name="parame"></param>
        /// <returns></returns>
        public async Task<int> AddAsync(AddUsersModelReceive parame)
        {
            var users = await _userRepository.Find(x => x.Account == parame.Account);
            if (users != null)
            {
                throw new DomainException("该账号已存在");
            }

            await _userRepository.AddAsync(new Users(parame.UserName, parame.UserPassWord, parame.Account));

            return await _userRepository.AppUnitOfWork.SaveChangesAsync();

        }

        /// <summary>
        /// 修改系统用户
        /// </summary>
        /// <param name="parame"></param>
        /// <returns></returns>
        public async Task<bool> ModifyAsync(ModifyUsersModelRequest parame)
        {
            var users = await _userRepository.Find(x => x.KeyId == parame.KeyId);
            if (users == null)
            {
                throw new DomainException("该账号不存在");
            }
            users.SetUpdateTime();
            _userRepository.UpdateAsync(users);
            await _userRepository.AppUnitOfWork.SaveChangesAsync();
            return true;
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="keyIdGuids"></param>
        /// <returns></returns>
        public async Task<int> RemoveAsync(params Guid[] keyIdGuids)
        {
            _userRepository.RemoveAsync(keyIdGuids);
            return await _userRepository.AppUnitOfWork.SaveChangesAsync();
        }

    }
}
